{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "A Convolutional Network implementation example using TensorFlow library.\n",
    "This example is using the MNIST database of handwritten digits\n",
    "(http://yann.lecun.com/exdb/mnist/)\n",
    "\n",
    "Author: Aymeric Damien\n",
    "Project: https://github.com/aymericdamien/TensorFlow-Examples/\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "# Import MNIST data\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Parameters\n",
    "learning_rate = 0.001\n",
    "training_iters = 200000\n",
    "batch_size = 128\n",
    "display_step = 10\n",
    "\n",
    "# Network Parameters\n",
    "n_input = 784 # MNIST data input (img shape: 28*28)\n",
    "n_classes = 10 # MNIST total classes (0-9 digits)\n",
    "dropout = 0.75 # Dropout, probability to keep units\n",
    "\n",
    "# tf Graph input\n",
    "x = tf.placeholder(tf.float32, [None, n_input])\n",
    "y = tf.placeholder(tf.float32, [None, n_classes])\n",
    "keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Create some wrappers for simplicity\n",
    "def conv2d(x, W, b, strides=1):\n",
    "    # Conv2D wrapper, with bias and relu activation\n",
    "    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n",
    "    x = tf.nn.bias_add(x, b)\n",
    "    return tf.nn.relu(x)\n",
    "\n",
    "\n",
    "def maxpool2d(x, k=2):\n",
    "    # MaxPool2D wrapper\n",
    "    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],\n",
    "                          padding='SAME')\n",
    "\n",
    "\n",
    "# Create model\n",
    "def conv_net(x, weights, biases, dropout):\n",
    "    # Reshape input picture\n",
    "    x = tf.reshape(x, shape=[-1, 28, 28, 1])\n",
    "\n",
    "    # Convolution Layer\n",
    "    conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n",
    "    # Max Pooling (down-sampling)\n",
    "    conv1 = maxpool2d(conv1, k=2)\n",
    "\n",
    "    # Convolution Layer\n",
    "    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n",
    "    # Max Pooling (down-sampling)\n",
    "    conv2 = maxpool2d(conv2, k=2)\n",
    "\n",
    "    # Fully connected layer\n",
    "    # Reshape conv2 output to fit fully connected layer input\n",
    "    fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])\n",
    "    fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n",
    "    fc1 = tf.nn.relu(fc1)\n",
    "    # Apply Dropout\n",
    "    fc1 = tf.nn.dropout(fc1, dropout)\n",
    "\n",
    "    # Output, class prediction\n",
    "    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n",
    "    return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Store layers weight & bias\n",
    "weights = {\n",
    "    # 5x5 conv, 1 input, 32 outputs\n",
    "    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),\n",
    "    # 5x5 conv, 32 inputs, 64 outputs\n",
    "    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),\n",
    "    # fully connected, 7*7*64 inputs, 1024 outputs\n",
    "    'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),\n",
    "    # 1024 inputs, 10 outputs (class prediction)\n",
    "    'out': tf.Variable(tf.random_normal([1024, n_classes]))\n",
    "}\n",
    "\n",
    "biases = {\n",
    "    'bc1': tf.Variable(tf.random_normal([32])),\n",
    "    'bc2': tf.Variable(tf.random_normal([64])),\n",
    "    'bd1': tf.Variable(tf.random_normal([1024])),\n",
    "    'out': tf.Variable(tf.random_normal([n_classes]))\n",
    "}\n",
    "\n",
    "# Construct model\n",
    "pred = conv_net(x, weights, biases, keep_prob)\n",
    "\n",
    "# Define loss and optimizer\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\n",
    "optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n",
    "\n",
    "# Evaluate model\n",
    "correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "\n",
    "# Initializing the variables\n",
    "init = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Iter 1280, Minibatch Loss= 26574.855469, Training Accuracy= 0.25781\n",
      "Iter 2560, Minibatch Loss= 11454.494141, Training Accuracy= 0.49219\n",
      "Iter 3840, Minibatch Loss= 10070.515625, Training Accuracy= 0.55469\n",
      "Iter 5120, Minibatch Loss= 4008.586426, Training Accuracy= 0.78125\n",
      "Iter 6400, Minibatch Loss= 3148.004639, Training Accuracy= 0.80469\n",
      "Iter 7680, Minibatch Loss= 6740.440430, Training Accuracy= 0.71875\n",
      "Iter 8960, Minibatch Loss= 4103.991699, Training Accuracy= 0.80469\n",
      "Iter 10240, Minibatch Loss= 2631.275391, Training Accuracy= 0.85938\n",
      "Iter 11520, Minibatch Loss= 1428.798828, Training Accuracy= 0.91406\n",
      "Iter 12800, Minibatch Loss= 3909.772705, Training Accuracy= 0.78906\n",
      "Iter 14080, Minibatch Loss= 1423.095947, Training Accuracy= 0.88281\n",
      "Iter 15360, Minibatch Loss= 1524.569824, Training Accuracy= 0.89062\n",
      "Iter 16640, Minibatch Loss= 2234.539795, Training Accuracy= 0.86719\n",
      "Iter 17920, Minibatch Loss= 933.932800, Training Accuracy= 0.90625\n",
      "Iter 19200, Minibatch Loss= 2039.046021, Training Accuracy= 0.89062\n",
      "Iter 20480, Minibatch Loss= 674.179932, Training Accuracy= 0.95312\n",
      "Iter 21760, Minibatch Loss= 3778.958984, Training Accuracy= 0.82812\n",
      "Iter 23040, Minibatch Loss= 1038.217773, Training Accuracy= 0.91406\n",
      "Iter 24320, Minibatch Loss= 1689.513672, Training Accuracy= 0.89062\n",
      "Iter 25600, Minibatch Loss= 1800.954956, Training Accuracy= 0.85938\n",
      "Iter 26880, Minibatch Loss= 1086.292847, Training Accuracy= 0.90625\n",
      "Iter 28160, Minibatch Loss= 656.042847, Training Accuracy= 0.94531\n",
      "Iter 29440, Minibatch Loss= 1210.589844, Training Accuracy= 0.91406\n",
      "Iter 30720, Minibatch Loss= 1099.606323, Training Accuracy= 0.90625\n",
      "Iter 32000, Minibatch Loss= 1073.128174, Training Accuracy= 0.92969\n",
      "Iter 33280, Minibatch Loss= 518.844543, Training Accuracy= 0.95312\n",
      "Iter 34560, Minibatch Loss= 540.856689, Training Accuracy= 0.92188\n",
      "Iter 35840, Minibatch Loss= 353.990906, Training Accuracy= 0.97656\n",
      "Iter 37120, Minibatch Loss= 1488.962891, Training Accuracy= 0.91406\n",
      "Iter 38400, Minibatch Loss= 231.191864, Training Accuracy= 0.98438\n",
      "Iter 39680, Minibatch Loss= 171.154480, Training Accuracy= 0.98438\n",
      "Iter 40960, Minibatch Loss= 2092.023682, Training Accuracy= 0.90625\n",
      "Iter 42240, Minibatch Loss= 480.594299, Training Accuracy= 0.95312\n",
      "Iter 43520, Minibatch Loss= 504.128143, Training Accuracy= 0.96875\n",
      "Iter 44800, Minibatch Loss= 143.534485, Training Accuracy= 0.97656\n",
      "Iter 46080, Minibatch Loss= 325.875580, Training Accuracy= 0.96094\n",
      "Iter 47360, Minibatch Loss= 602.813049, Training Accuracy= 0.91406\n",
      "Iter 48640, Minibatch Loss= 794.595093, Training Accuracy= 0.94531\n",
      "Iter 49920, Minibatch Loss= 415.539032, Training Accuracy= 0.95312\n",
      "Iter 51200, Minibatch Loss= 146.016022, Training Accuracy= 0.96094\n",
      "Iter 52480, Minibatch Loss= 294.180786, Training Accuracy= 0.94531\n",
      "Iter 53760, Minibatch Loss= 50.955730, Training Accuracy= 0.99219\n",
      "Iter 55040, Minibatch Loss= 1026.607056, Training Accuracy= 0.92188\n",
      "Iter 56320, Minibatch Loss= 283.756134, Training Accuracy= 0.96875\n",
      "Iter 57600, Minibatch Loss= 691.538208, Training Accuracy= 0.95312\n",
      "Iter 58880, Minibatch Loss= 491.075073, Training Accuracy= 0.96094\n",
      "Iter 60160, Minibatch Loss= 571.951660, Training Accuracy= 0.95312\n",
      "Iter 61440, Minibatch Loss= 284.041168, Training Accuracy= 0.97656\n",
      "Iter 62720, Minibatch Loss= 1041.941528, Training Accuracy= 0.92969\n",
      "Iter 64000, Minibatch Loss= 664.833923, Training Accuracy= 0.93750\n",
      "Iter 65280, Minibatch Loss= 1582.112793, Training Accuracy= 0.88281\n",
      "Iter 66560, Minibatch Loss= 783.135376, Training Accuracy= 0.94531\n",
      "Iter 67840, Minibatch Loss= 245.942398, Training Accuracy= 0.96094\n",
      "Iter 69120, Minibatch Loss= 752.858948, Training Accuracy= 0.96875\n",
      "Iter 70400, Minibatch Loss= 623.243286, Training Accuracy= 0.94531\n",
      "Iter 71680, Minibatch Loss= 846.498230, Training Accuracy= 0.93750\n",
      "Iter 72960, Minibatch Loss= 586.516479, Training Accuracy= 0.95312\n",
      "Iter 74240, Minibatch Loss= 92.774963, Training Accuracy= 0.98438\n",
      "Iter 75520, Minibatch Loss= 644.039612, Training Accuracy= 0.95312\n",
      "Iter 76800, Minibatch Loss= 693.247681, Training Accuracy= 0.96094\n",
      "Iter 78080, Minibatch Loss= 466.491882, Training Accuracy= 0.96094\n",
      "Iter 79360, Minibatch Loss= 964.212341, Training Accuracy= 0.93750\n",
      "Iter 80640, Minibatch Loss= 230.451904, Training Accuracy= 0.97656\n",
      "Iter 81920, Minibatch Loss= 280.434570, Training Accuracy= 0.95312\n",
      "Iter 83200, Minibatch Loss= 213.208252, Training Accuracy= 0.97656\n",
      "Iter 84480, Minibatch Loss= 774.836060, Training Accuracy= 0.94531\n",
      "Iter 85760, Minibatch Loss= 164.687729, Training Accuracy= 0.96094\n",
      "Iter 87040, Minibatch Loss= 419.967407, Training Accuracy= 0.96875\n",
      "Iter 88320, Minibatch Loss= 160.920151, Training Accuracy= 0.96875\n",
      "Iter 89600, Minibatch Loss= 586.063599, Training Accuracy= 0.96094\n",
      "Iter 90880, Minibatch Loss= 345.598145, Training Accuracy= 0.96875\n",
      "Iter 92160, Minibatch Loss= 931.361145, Training Accuracy= 0.92188\n",
      "Iter 93440, Minibatch Loss= 170.107117, Training Accuracy= 0.97656\n",
      "Iter 94720, Minibatch Loss= 497.162750, Training Accuracy= 0.93750\n",
      "Iter 96000, Minibatch Loss= 906.600464, Training Accuracy= 0.94531\n",
      "Iter 97280, Minibatch Loss= 303.382202, Training Accuracy= 0.92969\n",
      "Iter 98560, Minibatch Loss= 509.161652, Training Accuracy= 0.97656\n",
      "Iter 99840, Minibatch Loss= 359.561981, Training Accuracy= 0.97656\n",
      "Iter 101120, Minibatch Loss= 136.516541, Training Accuracy= 0.97656\n",
      "Iter 102400, Minibatch Loss= 517.199341, Training Accuracy= 0.96875\n",
      "Iter 103680, Minibatch Loss= 487.793335, Training Accuracy= 0.95312\n",
      "Iter 104960, Minibatch Loss= 407.351929, Training Accuracy= 0.96094\n",
      "Iter 106240, Minibatch Loss= 70.495193, Training Accuracy= 0.98438\n",
      "Iter 107520, Minibatch Loss= 344.783508, Training Accuracy= 0.96094\n",
      "Iter 108800, Minibatch Loss= 242.682465, Training Accuracy= 0.95312\n",
      "Iter 110080, Minibatch Loss= 169.181458, Training Accuracy= 0.96094\n",
      "Iter 111360, Minibatch Loss= 152.638245, Training Accuracy= 0.98438\n",
      "Iter 112640, Minibatch Loss= 170.795868, Training Accuracy= 0.96875\n",
      "Iter 113920, Minibatch Loss= 133.262726, Training Accuracy= 0.98438\n",
      "Iter 115200, Minibatch Loss= 296.063293, Training Accuracy= 0.95312\n",
      "Iter 116480, Minibatch Loss= 254.247543, Training Accuracy= 0.96094\n",
      "Iter 117760, Minibatch Loss= 506.795715, Training Accuracy= 0.94531\n",
      "Iter 119040, Minibatch Loss= 446.006897, Training Accuracy= 0.96094\n",
      "Iter 120320, Minibatch Loss= 149.467377, Training Accuracy= 0.97656\n",
      "Iter 121600, Minibatch Loss= 52.783600, Training Accuracy= 0.98438\n",
      "Iter 122880, Minibatch Loss= 49.041794, Training Accuracy= 0.98438\n",
      "Iter 124160, Minibatch Loss= 184.371246, Training Accuracy= 0.97656\n",
      "Iter 125440, Minibatch Loss= 129.838501, Training Accuracy= 0.97656\n",
      "Iter 126720, Minibatch Loss= 288.006531, Training Accuracy= 0.96875\n",
      "Iter 128000, Minibatch Loss= 187.284653, Training Accuracy= 0.97656\n",
      "Iter 129280, Minibatch Loss= 197.969955, Training Accuracy= 0.96875\n",
      "Iter 130560, Minibatch Loss= 299.969818, Training Accuracy= 0.96875\n",
      "Iter 131840, Minibatch Loss= 537.602173, Training Accuracy= 0.96094\n",
      "Iter 133120, Minibatch Loss= 4.519302, Training Accuracy= 0.99219\n",
      "Iter 134400, Minibatch Loss= 133.264191, Training Accuracy= 0.97656\n",
      "Iter 135680, Minibatch Loss= 89.662292, Training Accuracy= 0.97656\n",
      "Iter 136960, Minibatch Loss= 107.774078, Training Accuracy= 0.96875\n",
      "Iter 138240, Minibatch Loss= 335.904572, Training Accuracy= 0.96094\n",
      "Iter 139520, Minibatch Loss= 457.494568, Training Accuracy= 0.96094\n",
      "Iter 140800, Minibatch Loss= 259.131531, Training Accuracy= 0.95312\n",
      "Iter 142080, Minibatch Loss= 152.205383, Training Accuracy= 0.96094\n",
      "Iter 143360, Minibatch Loss= 252.535828, Training Accuracy= 0.95312\n",
      "Iter 144640, Minibatch Loss= 109.477585, Training Accuracy= 0.96875\n",
      "Iter 145920, Minibatch Loss= 24.468613, Training Accuracy= 0.99219\n",
      "Iter 147200, Minibatch Loss= 51.722107, Training Accuracy= 0.97656\n",
      "Iter 148480, Minibatch Loss= 69.715233, Training Accuracy= 0.97656\n",
      "Iter 149760, Minibatch Loss= 405.289246, Training Accuracy= 0.92969\n",
      "Iter 151040, Minibatch Loss= 282.976379, Training Accuracy= 0.95312\n",
      "Iter 152320, Minibatch Loss= 134.991119, Training Accuracy= 0.97656\n",
      "Iter 153600, Minibatch Loss= 491.618103, Training Accuracy= 0.92188\n",
      "Iter 154880, Minibatch Loss= 154.299988, Training Accuracy= 0.99219\n",
      "Iter 156160, Minibatch Loss= 79.480019, Training Accuracy= 0.96875\n",
      "Iter 157440, Minibatch Loss= 68.093750, Training Accuracy= 0.99219\n",
      "Iter 158720, Minibatch Loss= 459.739685, Training Accuracy= 0.92188\n",
      "Iter 160000, Minibatch Loss= 168.076843, Training Accuracy= 0.94531\n",
      "Iter 161280, Minibatch Loss= 256.141846, Training Accuracy= 0.97656\n",
      "Iter 162560, Minibatch Loss= 236.400391, Training Accuracy= 0.94531\n",
      "Iter 163840, Minibatch Loss= 177.011261, Training Accuracy= 0.96875\n",
      "Iter 165120, Minibatch Loss= 48.583298, Training Accuracy= 0.97656\n",
      "Iter 166400, Minibatch Loss= 413.800293, Training Accuracy= 0.96094\n",
      "Iter 167680, Minibatch Loss= 209.587387, Training Accuracy= 0.96875\n",
      "Iter 168960, Minibatch Loss= 239.407318, Training Accuracy= 0.98438\n",
      "Iter 170240, Minibatch Loss= 183.567017, Training Accuracy= 0.96875\n",
      "Iter 171520, Minibatch Loss= 87.937515, Training Accuracy= 0.96875\n",
      "Iter 172800, Minibatch Loss= 203.777039, Training Accuracy= 0.98438\n",
      "Iter 174080, Minibatch Loss= 566.378052, Training Accuracy= 0.94531\n",
      "Iter 175360, Minibatch Loss= 325.170898, Training Accuracy= 0.95312\n",
      "Iter 176640, Minibatch Loss= 300.142212, Training Accuracy= 0.97656\n",
      "Iter 177920, Minibatch Loss= 205.370193, Training Accuracy= 0.95312\n",
      "Iter 179200, Minibatch Loss= 5.594437, Training Accuracy= 0.99219\n",
      "Iter 180480, Minibatch Loss= 110.732109, Training Accuracy= 0.98438\n",
      "Iter 181760, Minibatch Loss= 33.320297, Training Accuracy= 0.99219\n",
      "Iter 183040, Minibatch Loss= 6.885544, Training Accuracy= 0.99219\n",
      "Iter 184320, Minibatch Loss= 221.144806, Training Accuracy= 0.96875\n",
      "Iter 185600, Minibatch Loss= 365.337372, Training Accuracy= 0.94531\n",
      "Iter 186880, Minibatch Loss= 186.558258, Training Accuracy= 0.96094\n",
      "Iter 188160, Minibatch Loss= 149.720322, Training Accuracy= 0.98438\n",
      "Iter 189440, Minibatch Loss= 105.281998, Training Accuracy= 0.97656\n",
      "Iter 190720, Minibatch Loss= 289.980011, Training Accuracy= 0.96094\n",
      "Iter 192000, Minibatch Loss= 214.382278, Training Accuracy= 0.96094\n",
      "Iter 193280, Minibatch Loss= 461.044312, Training Accuracy= 0.93750\n",
      "Iter 194560, Minibatch Loss= 138.653076, Training Accuracy= 0.98438\n",
      "Iter 195840, Minibatch Loss= 112.004883, Training Accuracy= 0.98438\n",
      "Iter 197120, Minibatch Loss= 212.691467, Training Accuracy= 0.97656\n",
      "Iter 198400, Minibatch Loss= 57.642502, Training Accuracy= 0.97656\n",
      "Iter 199680, Minibatch Loss= 80.503563, Training Accuracy= 0.96875\n",
      "Optimization Finished!\n",
      "Testing Accuracy: 0.984375\n"
     ]
    }
   ],
   "source": [
    "# Launch the graph\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    step = 1\n",
    "    # Keep training until reach max iterations\n",
    "    while step * batch_size < training_iters:\n",
    "        batch_x, batch_y = mnist.train.next_batch(batch_size)\n",
    "        # Run optimization op (backprop)\n",
    "        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,\n",
    "                                       keep_prob: dropout})\n",
    "        if step % display_step == 0:\n",
    "            # Calculate batch loss and accuracy\n",
    "            loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,\n",
    "                                                              y: batch_y,\n",
    "                                                              keep_prob: 1.})\n",
    "            print(\"Iter \" + str(step*batch_size) + \", Minibatch Loss= \" + \\\n",
    "                  \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \\\n",
    "                  \"{:.5f}\".format(acc))\n",
    "        step += 1\n",
    "    print(\"Optimization Finished!\")\n",
    "\n",
    "    # Calculate accuracy for 256 mnist test images\n",
    "    print(\"Testing Accuracy:\", \\\n",
    "        sess.run(accuracy, feed_dict={x: mnist.test.images[:256],\n",
    "                                      y: mnist.test.labels[:256],\n",
    "                                      keep_prob: 1.}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
